import React from "react";
import { Icon } from "./index";
import type { IconProps } from "./index";

const loadedSet = new Set<string>();

export const createFromIconfont = (iconfontUrl: string) => {
  if (
    typeof iconfontUrl === "string" &&
    iconfontUrl.length &&
    !loadedSet.has(iconfontUrl)
  ) {
    const script = document.createElement("script");
    script.setAttribute("src", iconfontUrl);
    script.setAttribute("data-namespace", iconfontUrl);
    document.body.appendChild(script);

    loadedSet.add(iconfontUrl);
  }

  const Iconfont = React.forwardRef<SVGSVGElement, IconProps>((props, ref) => {
    const { type, ...rest } = props;

    return (
      <Icon {...rest} ref={ref}>
        {type ? <use xlinkHref={`#${type}`} /> : null}
      </Icon>
    );
  });

  return Iconfont;
};
